<?php

if (!defined('PATH'))
	exit();

//*todo* add .htaccess to guild images

class Guilds extends Controller {

	protected $default_action = 'list';
	public $_title = 'Guilds';

	public function __construct() {
		parent::__construct();
	}

	public function getAccess(OTS_Guild $_guild) {
		$array = array('access' => array('owner' => false, 'leader' => false, 'vice' => false, 'member' => false), 'playersFromAccountInGuild' => array());
		if (LOGGED) {
			$rankList = $_guild->getGuildRanksList();
			$rankList->orderBy('level', POT::ORDER_DESC);
			$account = $this->archez->getLogged();
			$accountCharacters = $account->getPlayers();
			if (!empty($accountCharacters)) {
				foreach ($accountCharacters as $player) {
					$playerRank = $player->getRank();
					if (!$playerRank) {
						continue;
					}
					$playerGuild = $playerRank->getGuild();
					if (!$playerGuild->isLoaded()) {
						continue;
					}
					if ($playerGuild->getId() != $_guild->getId()) {
						continue;
					}
					if ($_guild->getOwner()->getId() == $player->getId()) {
						$array['access']['owner'] = true;
						$array['access']['leader'] = true;
						$array['access']['vice'] = true;
						$array['access']['member'] = true;
						$array['playersFromAccountInGuild'][] = $player->getId();
						continue;
					}
					if ($playerRank->getLevel() > 2) {
						$array['access']['leader'] = true;
						$array['access']['vice'] = true;
						$array['access']['member'] = true;
						$array['playersFromAccountInGuild'][] = $player->getId();
						continue;
					}
					if ($playerRank->getLevel() > 1) {
						$array['access']['vice'] = true;
						$array['access']['member'] = true;
						$array['playersFromAccountInGuild'][] = $player->getId();
						continue;
					}
					if ($playerRank->getLevel() > 0) {
						$array['access']['member'] = true;
						$array['playersFromAccountInGuild'][] = $player->getId();
						continue;
					}
				}
			}
		}
		return $array;
	}

	private function invite(OTS_Guild $_guild) {

	}

	private function cancel_invite(OTS_Guild $_guild) {
		if (isset($_POST['submit'])) {
			if (!isset($_POST['player'])) {
				$this->archez->showMsg('Nice try. Get out :)', 'error');
				return;
			}

		} else {
			$this->redirect(PATH . '/guilds/show/'.$_guild->getId().'/');
		}
	}

	private function delete_invite(OTS_Guild $_guild) {

	}

	private function accept_invite(OTS_Guild $_guild) {
		if (isset($_POST['submit'])) {
			if (!isset($_POST['player'])) {
				$this->archez->showMsg('Nice try. Get out :)', 'error');
				return;
			}

		} else {
			$this->redirect(PATH . '/guilds/show/'.$_guild->getId().'/');
		}
	}

	private function kick(OTS_Guild $_guild) {

	}

	private function leave(OTS_Guild $_guild) {

	}

	private function delete(OTS_Guild $_guild) {

	}

	private function pass_ownership(OTS_Guild $_guild) {

	}

	private function create_rank(OTS_Guild $_guild) {

	}

	private function change_rank(OTS_Guild $_guild) {

	}

	private function delete_rank(OTS_Guild $_guild) {

	}

	private function change_description(OTS_Guild $_guild) { // only leader
		$roles = $this->getAccess($_guild);
		if (!$roles['access']['leader']) {
			$this->archez->showMsg('You don\'t have access to do it, <a href="' . PATH . '/guilds/show/'.$_guild->getId().'/">click here</a> to go back.', 'error');
		} else {
			if (isset($_POST['submit'])) {
				$description = htmlspecialchars(stripslashes(substr(trim($_POST['description']),0,$this->config['website']['guild']['descriptionCharactersLimit'])));
				$_guild->setCustomField('description', $description);
				$this->archez->showMsg('Guild description has been changed, <a href="' . PATH . '/guilds/management/'.$_guild->getId().'/">click here</a> to go back.', 'success');
			} else {
				$view = new View('guilds/management/description_form');
				$view->guild = $_guild;
				$view->render();
			}
		}
	}

	private function change_logo(OTS_Guild $_guild) { // only owner
		$roles = $this->getAccess($_guild);
		if (!$roles['access']['owner']) {
			$this->archez->showMsg('You don\'t have access to do it, <a href="' . PATH . '/guilds/show/'.$_guild->getId().'/">click here</a> to go back.', 'error');
		} else {
			if (isset($_POST['submit'])) {
				if ($_POST['MAX_FILE_SIZE'] != (50*1024)) {
					$this->archez->showMsg('Nice try. Get out :)', 'error');
					return;
				}
				if (!Helper_FileUpload::isLoaded('img')) {
					$this->archez->showMsg('Please select file, <a href="' . PATH . '/guilds/show/'.$_guild->getId().'/">click here</a> to go back.', 'error');
					return;
				}
				if (Helper_FileUpload::getExtUploadedFile('img') != $this->config['website']['guild']['ext']) {
					$this->archez->showMsg('Wrong extension of file(should be '.$this->config['website']['guild']['ext'].'), <a href="' . PATH . '/guilds/show/'.$_guild->getId().'/">click here</a> to go back.', 'error');
					return;
				}
				$size = Helper_FileUpload::getImageSize('img');
				if ($size[0] != 64 || $size[1] != 64) {
					$this->archez->showMsg('Wrong size of file(should be 64x64 in pixels), <a href="' . PATH . '/guilds/show/'.$_guild->getId().'/">click here</a> to go back.', 'error');
					return;
				}
				Helper_FileUpload::saveUploadedFile('img', $this->config['global']['real_path'].'/media/images/guild_logo/', true, $_guild->getId().'.'.$this->config['website']['guild']['ext']);
				$this->archez->showMsg('Guild logo has been changed, <a href="' . PATH . '/guilds/management/'.$_guild->getId().'/">click here</a> to go back.', 'success');
			} else {
				$view = new View('guilds/management/logo_form');
				$view->guild = $_guild;
				$view->render();
			}
		}
	}

	private function change_motd(OTS_Guild $_guild) { // only leader
		$roles = $this->getAccess($_guild);
		if (!$roles['access']['leader']) {
			$this->archez->showMsg('You don\'t have access to do it, <a href="' . PATH . '/guilds/show/'.$_guild->getId().'/">click here</a> to go back.', 'error');
		} else {
			if (isset($_POST['submit'])) {
				$motd = htmlspecialchars(stripslashes(substr(trim($_POST['motd']),0,$this->config['website']['guild']['motdCharactersLimit'])));
				$_guild->setCustomField('motd', $motd);
				$this->archez->showMsg('Guild motd has been changed, <a href="' . PATH . '/guilds/management/'.$_guild->getId().'/">click here</a> to go back.', 'success');
			} else {
				$view = new View('guilds/management/motd_form');
				$view->guild = $_guild;
				$view->render();
			}
		}
	}

	private function change_nick(OTS_Guild $_guild) { // leader can edit whole nicks
		if (!isset($_POST['player'])) {
			$this->archez->showMsg('You\'re trying to execute SQL Injection. Nice try. Get out :)', 'error');
			return;
		}
		$player = $this->ots->createObject('Player');
		$player->load($_POST['player']);
		if (!$player->isLoaded()) {
			$this->archez->showMsg('You\'re trying to execute SQL Injection. Nice try. Get out :)', 'error');
			return;
		}
		$roles = $this->getAccess($_guild);
		if (!in_array($player->getId(), $roles['playersFromAccountInGuild']) && !$roles['access']['leader']) {
			$this->archez->showMsg('You\'re trying to execute SQL Injection. Nice try. Get out :)', 'error');
			return;
		}

		if ($player->isOnline()) {
			$this->archez->showMsg('Character should be offline in game, <a href="' . PATH . '/guilds/show/'.$_guild->getId().'/">click here</a> to go back.', 'error');
			return;
		}

		$nick = Helper_General::clean($_POST['nick']);
		if (!$this->archez->checkGuildNick($nick)) {
			$this->archez->showMsg('Invalid or too long nick, <a href="' . PATH . '/guilds/show/'.$_guild->getId().'/">click here</a> to go back.', 'error');
			return;
		}

		$player->setGuildNick($nick);
		$player->save();

		$this->archez->showMsg('Character guild nick has been changed, <a href="' . PATH . '/guilds/show/'.$_guild->getId().'/">click here</a> to go back.', 'success');
	}

	public function action_create() {
		if (LOGGED) {
			$account = $this->archez->getLogged();
			$premmy = true;
			if ($this->config['website']['guild']['premmyToCreate'] && !$account->isPremium()) {
				$premmy = false;
			}
			if (!$premmy) {
				$this->archez->showMsg('You need a premium account to create new guild.', 'error');
			} else {
				if (isset($_POST['selected_character'])) {
					$player = $this->ots->createObject('Player');
					$player->find($_POST['character']);
					if (!$player->isLoaded()) {
						$this->archez->showMsg('Player doesn\'t exist, <a href="' . PATH . '/guilds/create">click here</a> to go back.', 'error');
					} else if ($player->getAccount()->getId() != $account->getId()) {
						$this->archez->showMsg('Player isn\'t on your account, <a href="' . PATH . '/guilds/create">click here</a> to go back.', 'error');
					} else if ($player->isDeleted()) {
						$this->archez->showMsg('Player is deleted, <a href="' . PATH . '/guilds/create">click here</a> to go back.', 'error');
					} else if ($player->getRank()) {
						$this->archez->showMsg('Player is already in a guild, <a href="' . PATH . '/guilds/create">click here</a> to go back.', 'error');
					} else if ($player->getLevel() < $this->config['website']['guild']['levelToCreate']) {
						$this->archez->showMsg('Player has got too low level, <a href="' . PATH . '/guilds/create">click here</a> to go back.', 'error');
					} else {
						$_SESSION['guildCharacter'] = $player->getId();
						$view = new View('guilds/create_data_form');
						$view->render();
					}
				} else if (isset($_POST['finish'])) {
					if (isset($_SESSION['guildCharacter'])) {
						$guild = $this->ots->createObject('Guild');
						$guild->find($_POST['guild_name']);
						if (empty($_POST['guild_name'])) {
							$this->archez->showMsg('Please fill guild name, <a href="' . PATH . '/guilds/create">click here</a> to go back.', 'error');
						} else if ($guild->isLoaded()) {
							$this->archez->showMsg('Guild with this name already exists, <a href="' . PATH . '/guilds/create">click here</a> to go back.', 'error');
						} else if (!$this->archez->checkGuildName($_POST['guild_name'])) {
							$this->archez->showMsg('Wrong format of guild name, <a href="' . PATH . '/guilds/create">click here</a> to go back.', 'error');
						} else {
							$player = $this->ots->createObject('Player');
							$player->load($_SESSION['guildCharacter']);
							$guild->setName($_POST['guild_name']);
							$guild->setOwner($player);
							$guild->setCreationData(time());
							$guild->save();
							$guild->setCustomField('description', 'Default description.');
							$guild->setCustomField('world_id', $player->getWorld());
							$ranks = $guild->getGuildRanksList();
							$ranks->orderBy('level', POT::ORDER_DESC);
							foreach ($ranks as $rank) {
								if ($rank->getLevel() == 3) {
									$player->setRank($rank);
									$player->save();
									break;
								}
							}
							$this->archez->showMsg('You have created guild <b>' . $guild->getName() . '</b>. <b>' . $player->getName() . '</b> is leader of this guild. Now you can invite players, change picture, description and motd of guild, <a href="' . PATH . '/guilds/management">click here</a> to go a management.', 'success');
						}
					} else {
						$this->redirect(PATH . '/guilds/create/');
					}
				} else {
					$view = new View('guilds/create_select_character');
					$view->account = $account;
					$view->render();
				}
			}
		} else {
			$this->archez->showMsg('You must <a href="' . PATH . '/account/login/guilds/create/">log in</a> first.', 'notice');
		}
	}

	public function action_show() {
		$guild = $this->ots->createObject('Guild');
		$guild->load($this->paramsURI[2]);
		if (!$guild->isLoaded())
			$this->archez->showMsg('Guild doesn\'t exist, <a href="' . PATH . '/guilds/">click here</a> to go back.', 'error');
		else {
			$roles = $this->getAccess($guild);
			$view = new View('guilds/show');
			$view->guild = $guild;
			$view->roles = $roles;
			$view->render();
		}
	}

	public function action_management() { // guilds/management/{guild_id}/{action}/{subparams}
		if (LOGGED) {
			if (!isset($this->paramsURI[2])) {

			}
			$guild = $this->ots->createObject('Guild');
			$guild->load($this->paramsURI[2]);
			if (!$guild->isLoaded()) {
				$this->redirect(PATH . '/guilds/');
			}

			if (isset($this->paramsURI[3])) {
				switch ($this->paramsURI[3]) {

					case "invite_player":
						break;

					case "accept_invite":
						break;

					case "cancel_invite":
						break;

					case "delete_invite":
						break;

					case "delete":
						break;

					case "kick_player":
						break;

					case "leave":
						break;

					case "pass_ownership":
						break;

					case "create_rank":
						break;

					case "change_rank":
						break;

					case "delete_rank":
						break;

					case "change_logo":
						$this->change_logo($guild);
						break;

					case "change_description":
						$this->change_description($guild);
						break;

					case "change_motd":
						$this->change_motd($guild);
						break;

					case "change_nick":
						$this->change_nick($guild);
						break;

					default:
						$this->redirect(PATH . '/guilds/management/');
				}
			} else {
				$roles = $this->getAccess($guild);
				$view = new View('guilds/management_menu');
				$view->roles = $roles;
				$view->render();
			}
		} else {
			$this->archez->showMsg('You must <a href="' . PATH . '/account/login/guilds/managament/">log in</a> first.', 'notice');
		}
	}

	public function action_list() {
		$this->_title = "Guild List";
		$guildsList = $this->ots->createObject('Guilds_List');
		$guildsList->orderBy('name');
		$view = new View('guilds/list');
		$view->guildList = $guildsList;
		$view->render();
	}

}

?>